package com.audaque.springboot.foshanupload.web.redisdemo.controller;

import com.audaque.springboot.foshanupload.web.redisdemo.service.IntegrationService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;


@RestController
@RequestMapping("integration")
@Log4j2
public class IntegrationController {
    @Autowired
    private RedisLockRegistry redisLockRegistry;


    @Autowired
    private IntegrationService integrationService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("/test3")
    public void test3() throws InterruptedException {

        while (true) {
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        integrationService.run3(null, null);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }


    @GetMapping("/test1")
    public void test1() {
        while (true) {
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    run1();
                }
            });
        }
    }

    private void run1() {
        Lock lock = redisLockRegistry.obtain("redis");
        try {
            //尝试在指定时间内加锁，如果已经有其他锁锁住，获取当前线程不能加锁，则返回false，加锁失败；加锁成功则返回true
            if (lock.tryLock(3, TimeUnit.SECONDS)) {
                log.debug("lock is ready");
            } else {
                log.debug("lock isnot ready");
            }
        } catch (InterruptedException e) {
            log.error("obtain lock error", e);
        } finally {
            lock.unlock();
        }
    }

}